package com.elf.zero.step;

import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;

import androidx.annotation.RequiresApi;

import com.elf.zero.utils.DateTimeUtils;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class StepJobService extends JobService {

    private final static String TAG = StepJobService.class.getSimpleName();
    private StepManger stepManger;

    @Override
    public boolean onStartJob(JobParameters params) {

        Step.writeLog(TAG + " onStartJob");

        stepManger = new StepManger(this);
        if (!stepManger.isSupport()) {
            return false;
        }
        stepManger.setListener(value -> {
            Step.writeLog(TAG + " jobFinished : step=" + value);
            jobFinished(params, true);
        });
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Step.writeLog(TAG + " onStopJob");
        stepManger.destroy();
        return false;
    }

    public static void start(Context context) {
        JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        JobInfo jobInfo = new JobInfo.Builder(1, new ComponentName(context, StepJobService.class))
//                .setMinimumLatency(5000)   //最小延迟
//                .setOverrideDeadline(5000)
//                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .setPersisted(true)     //系统重启后是否保留
                .setPeriodic(16 * DateTimeUtils.MINUTE)
                .setRequiresDeviceIdle(true)
                .build();
        jobScheduler.schedule(jobInfo);
    }
}
